package com.rrd.hive.udf;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import org.apache.hadoop.hive.ql.exec.UDF;


import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UaParseUDF extends UDF {
    public  static  final Pattern PATTERN = Pattern.compile(".*iPhone.*Mobile/(\\w+).*");

    public String evaluate(String ua) {
        if(ua==null || ua.equals("")){
            return "";
        }
        StringBuffer sb = new StringBuffer();
        try {
            UserAgent uagent = UserAgentUtil.parse(ua);
            sb.append(uagent.getOs()==null?"":uagent.getOs().toString()).append(",");
            sb.append(uagent.getOsVersion()==null?"":uagent.getOsVersion()).append(",");
            sb.append(uagent.getBrowser()==null?"":uagent.getBrowser().toString()).append(",");
            sb.append(uagent.getVersion()==null?"":uagent.getVersion()).append(",");
            sb.append(uagent.getEngine()==null?"":uagent.getEngine().toString()).append(",");
            sb.append(uagent.getEngineVersion()==null?"":uagent.getEngineVersion()).append(",");
            Matcher matcher = PATTERN.matcher(ua);
            if(matcher.matches()){
                sb.append(matcher.group(1)==null?"":matcher.group(1));
            }else{
                sb.append("");
            }
            sb.append(",1");
        } catch (Exception e){
            e.printStackTrace();
        }

        return  sb.toString();
    }
    public static void main(String[] args) throws IOException {
        String ua="Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 haohuan /sa-sdk-ios/sensors-verify/sensors.haohuan.com?production";
        ua="Mozilla/5.0 (Linux; Android 12; ELS-AN00 Build/HUAWEIELS-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/92.0.4515.105 Mobile Safari/537.36";
        ua="Mozilla/5.0 (iPhone; CPU iPhone OS 16_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148";

        UserAgent uagent = UserAgentUtil.parse(ua);
        System.out.println("浏览器名称："+uagent.getBrowser().toString());//Chrome
        System.out.println("浏览器版本："+uagent.getVersion());//14.0.835.163
        System.out.println("浏览器引擎："+uagent.getEngine().toString());//Webkit
        System.out.println("浏览器引擎版本："+uagent.getEngineVersion());//535.1
        System.out.println("操作系统："+uagent.getOs().toString());//Windows 7
        System.out.println("操作系统版本："+uagent.getOsVersion());
        System.out.println("操作平台："+uagent.getPlatform().toString());//Windows
        System.out.println("是否是移动端:" + uagent.isMobile());

        Matcher matcher = PATTERN.matcher(ua);
        if(matcher.matches()){
            System.out.println(matcher.group(1));
        }
    }
}
